//
//  AppPrivacyVC.swift
//  XiaoweHealthy
//
//  Created by Riven on 2022/7/18.
//

import UIKit
import SwiftRichString

class AppPrivacyVC: UIViewController, UITextViewDelegate {
    
    let appNameKey = "AppNameKey"
    let appUserAgreementKey = "AppUserAgreementKey"
    let appPrivacyPolicyKey = "AppPrivacyPolicyKey"
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
//        return appDefaultStatusBarStye
        return .lightContent
    }
    
//    private lazy var gradientLayer: CAGradientLayer = {
//        let gradientLayer = CAGradientLayer()
//        gradientLayer.colors = gradientColors.map({ $0.cgColor })
//        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
//        gradientLayer.endPoint = CGPoint(x: 0, y: 1)
//        gradientLayer.type = .axial
//        return gradientLayer
//    }()
//    private lazy var gradientColors: [UIColor] = [UIColor(hex: 0xD5F9E1)!, UIColor(hex: 0xF8F8F8)!]
    
    private lazy var bgImageView = UIImageView()
    
    private lazy var contentView = UIView()
    private lazy var titleLb = UILabel()
    private lazy var textView = UITextView()
    
    private lazy var agreeBtn = UIButton()
    private lazy var rejectBtn = UIButton()
    
    private lazy var normal = Style {
        $0.font = AppFont.harmonyOSSans(ofSize: 16, weight: .regular)
        $0.color = majorTextColor
        $0.lineSpacing = 10
    }
    private lazy var light = Style {
        $0.font = AppFont.harmonyOSSans(ofSize: 14, weight: .regular)
        $0.color = majorTextColor.withAlphaComponent(0.4)
        $0.lineSpacing = 8
    }
    
    private lazy var link1 = Style {
        $0.font = AppFont.harmonyOSSans(ofSize: 16, weight: .regular)
        $0.linkURL = URL(string: "link1")
    }
    
    private lazy var link2 = Style {
        $0.font = AppFont.harmonyOSSans(ofSize: 16, weight: .regular)
        $0.linkURL = URL(string: "link2")
    }
        
    private var privacyString1: String {
//        let tText =         "《\(Bundle.main.appDisplayName)用户协议》"
        let tText = R.string.localizable.appNameKey用户协议().replacingOccurrences(of: appNameKey, with: Bundle.main.appDisplayName.localized())
        
        return tText
    }
    private var privacyString2: String {
//        let tText = "《\(Bundle.main.appDisplayName)隐私政策》"
        
        let tText = R.string.localizable.appNameKey隐私政策().replacingOccurrences(of: appNameKey, with: Bundle.main.appDisplayName.localized())
        
        return tText
    }
    private var topText: String {
//        "在你使用\(Bundle.main.appDisplayName)APP前，请认真阅读并了解\(privacyString1)和\(privacyString2)，我们将按照政策和协议内容为您提供服务，我们会收集您的位置等信息，特向您说明如下："
        
        var tText = R.string.localizable.在你使用AppNameKey前请认真阅读并了解AppUserAgreementKey和AppPrivacyPolicyKey我们将按照政策和协议内容为您提供服务我们会收集您的位置等信息特向您说明如下()
        tText = tText.replacingOccurrences(of: appNameKey, with: Bundle.main.appDisplayName.localized())
        tText = tText.replacingOccurrences(of: appUserAgreementKey, with: privacyString1)
        tText = tText.replacingOccurrences(of: appPrivacyPolicyKey, with: privacyString2)

        return tText
    }
    
    private var bottomText: String {
//        "\n\n1：使用蓝牙音频设备连接功能时，我们需要你登录\(Bundle.main.appDisplayName)账号，并且可能会申请你的手机蓝牙权限\n2：我们将根据《隐私政策》收集对应功能所需的个人信息，我们将获取您的同意\n3：您可以修改、查询您的个人信息\n4：未经过您的同意，我们不会从第三方处获取、共享或提供您的信息\n"
        var tText = R.string.localizable.使用蓝牙音频设备连接功能时我们需要你登录AppNameKey账号并且可能会申请你的手机蓝牙权限2我们将根据隐私政策收集对应功能所需的个人信息我们将获取您的同意3您可以修改查询您的个人信息4未经过您的同意我们不会从第三方处获取共享或提供您的信息()
        tText = tText.replacingOccurrences(of: appNameKey, with: Bundle.main.appDisplayName.localized())

        return tText
    }
    
    var completion: (() -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavTransparent()
        navigationController?.isNavigationBarHidden = true
        
        addSubViews()
        
        textView.backgroundColor = .white
        
        let a1 = topText.set(style: normal)
        var sRange = (topText as NSString).range(of: privacyString1)
        a1.add(style: link1, range: sRange)
        sRange = (topText as NSString).range(of: privacyString2)
        a1.add(style: link2, range: sRange)
        let a2 = bottomText.set(style: light)
        textView.attributedText = a1 + a2
        
        textView.linkTextAttributes = [.foregroundColor: btnBgColor]
    }
    
    private func addSubViews() {
//        gradientLayer.frame = view.bounds
//        view.layer.insertSublayer(gradientLayer, at: 0)
        
        view.addSubview(bgImageView)
        
        view.addSubview(contentView)
        
        contentView.addSubview(titleLb)
        contentView.addSubview(textView)
        view.addSubview(agreeBtn)
        view.addSubview(rejectBtn)
        
        view.backgroundColor = .white
        contentView.layer.cornerRadius = 12
        contentView.layer.backgroundColor = UIColor.white.cgColor
        
        //        contentView.layer.cornerRadius = 16
        //        contentView.layer.backgroundColor = UIColor.white.cgColor
        
        let tFont = navTitleFont
        titleLb.font = tFont
        titleLb.textColor = majorTextColor
        titleLb.textAlignment = .left
        titleLb.numberOfLines = 0
        
//        let tText = "欢迎使用\(Bundle.main.appDisplayName)APP"
        let tText = R.string.localizable.欢迎使用AppNameKey().replacingOccurrences(of: appNameKey, with: Bundle.main.appDisplayName.localized())
//        titleLb.text = tText
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 10
        let attributes = [NSAttributedString.Key.font: tFont, NSAttributedString.Key.foregroundColor: majorTextColor, NSAttributedString.Key.paragraphStyle: paragraphStyle]
        let attrText = NSAttributedString(string: tText, attributes: attributes)
        titleLb.attributedText = attrText
        
        agreeBtn.titleLabel?.font = AppFont.harmonyOSSans(ofSize: 22, weight: .medium)
        agreeBtn.setTitleColor(.white, for: .normal)
        agreeBtn.addTarget(self, action: #selector(clickAgreeBtn), for: .touchUpInside)
        agreeBtn.layer.cornerRadius = 12
        agreeBtn.layer.backgroundColor = btnBgColor.cgColor
        
        rejectBtn.titleLabel?.font = AppFont.harmonyOSSans(ofSize: 22, weight: .medium)
        rejectBtn.setTitleColor(majorTextColor, for: .normal)
        rejectBtn.addTarget(self, action: #selector(clickRejectBtn), for: .touchUpInside)
        rejectBtn.layer.cornerRadius = 12
        rejectBtn.layer.backgroundColor = UIColor(hex: 0xE3E3E3).cgColor
        
        bgImageView.contentMode = .scaleAspectFill
        bgImageView.image = nil
        
        agreeBtn.setTitle(R.string.localizable.同意(), for: .normal)
        rejectBtn.setTitle(R.string.localizable.拒绝(), for: .normal)
        
        textView.isEditable = false
        textView.isSelectable = true
        textView.delegate = self
    }
    
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        
        relayoutSubViews()
    }
    
    private func relayoutSubViews() {
        var contentHeight: CGFloat = 564
        let tScreenHeight = UIScreen.main.bounds.height
        if tScreenHeight < 812 {
            contentHeight = contentHeight * (tScreenHeight / 812) - 10
        }
        
//        var yOffset: CGFloat = 16 + 44
//        if let isHidden = navigationController?.isNavigationBarHidden, isHidden {
//            yOffset = 16 + 44
//        }
        bgImageView.frame = UIScreen.main.bounds
        
        var yOffset: CGFloat = 64
        var xOffset: CGFloat = 34
        contentHeight = 500
        contentView.frame = CGRect(x: xOffset, y: view.safeAreaInsets.top + yOffset, width: view.width - xOffset * 2, height: contentHeight)
        
        xOffset = 20
        let contentWidth: CGFloat = contentView.width - xOffset * 2
        titleLb.frame = CGRect(x: xOffset, y: 20, width: contentWidth, height: 64)
        yOffset = titleLb.y + titleLb.height + 10
        textView.frame = CGRect(x: titleLb.x, y: yOffset, width: titleLb.width, height: 300)
        
        yOffset = textView.frame.maxY + 10 + contentView.y

        xOffset = contentView.x + titleLb.x
        let btnWidth = contentWidth
        let btnHeight: CGFloat = 50
        
        agreeBtn.frame = CGRect(x: xOffset, y: yOffset, width: btnWidth, height: btnHeight)
        
        yOffset = agreeBtn.frame.maxY + 10
        rejectBtn.frame = CGRect(x: xOffset, y: yOffset, width: btnWidth, height: btnHeight)
    }
    
    @objc private func clickAgreeBtn() {
        AppPrivacy.isShow = false
        completion?()
    }
    
    @objc private func clickRejectBtn() {
        exit(0)
    }
    
    // MARK: -
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//    }
    
//    override func viewDidAppear(_ animated: Bool) {
//        super.viewDidAppear(animated)
//
//        setNeedsStatusBarAppearanceUpdate()
//    }
    
    // MARK: - UITextViewDelegate
    func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    
        if url.absoluteString == "link1" {
//            AppSafari.gotoPrivacyProtocol(at: self)
            AppSafari.gotoUserProtocol(at: self)
            return false
        }
        
        if url.absoluteString == "link2" {
//            AppSafari.gotoUserProtocol(at: self)
            AppSafari.gotoPrivacyProtocol(at: self)
            return false
        }
        
        return true
    }

}
